import { Table, Pagination,Modal,Input,Button,Row, Col, Card, List, Tabs,Collapse,Tooltip,Divider, message,Select,Upload  } from 'antd';  
import { useState, useEffect } from 'react';  
import { list,delmark,addmark,editmark,getIngredientInfoById,getIngredientSubjectTestById,comparisonIngredient,importIngredientInfoCheck,importIngredientInfoSave,importSubject} from "@/api/modules/litermark";
import { useTranslation } from 'react-i18next';
import MyTabsComponent from './MyTabsComponent';
import { DownloadOutlined,UploadOutlined} from '@ant-design/icons';  
import {download,downloadArr} from '@/utils/request';
import FullscreenLoading from '@/components/FullscreenLoading';
import useCacheAlive from '@/hooks/useCacheAlive';
import './literMark.css'
import { getInfo } from "@/api/login/ssoLogin";
const { Option } = Select;

const literMark = () => {  
  const { t } = useTranslation()
  const [litermarklist, setLitermarklist] = useCacheAlive([], `table-litermark-litermarklist`) // 假设这是从某处获取的数据  
  const [titleList, setTitleList] = useCacheAlive([], `table-litermark-titleList`) // 假设这是从某处获取的数据  
  const [loading, setLoading] = useState(false); // 加载状态  
  const [total, setTotal] = useCacheAlive(0, `table-litermark-total`)  // 总条目数  
  const [currentPage, setCurrentPage] = useCacheAlive(1, `table-litermark-currentPage`)// 当前页码  
  const [pageSize, setPageSize] = useCacheAlive(10, `table-litermark-pageSize`)// 每页显示的条目数  
  const [sortedInfo, setSortedInfo] = useState(null); // 排序信息  
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选择的行keys  
  const [visible, setVisible] = useState(false);  
  const [selectedRow, setSelectedRow] = useState(null);  
  const [tabKey, setTabKey] = useState('1'); // 假设默认显示通用Tab  
  const { Panel } = Collapse; 
  const [tabData,setTabData] =  useCacheAlive([], `table-litermark-tabData`)
  const [tabSubjectLevel1,setTabSubjectLevel1] = useCacheAlive([], `table-litermark-tabSubjectLevel1`)
  const [formId,setFormId]  = useState(null)
  const [reportList,setReportList] = useCacheAlive([], `table-litermark-reportList`)
 // 搜索框的状态  
 const [ingredient, setIngredient] = useCacheAlive('', `table-litermark-ingredient`)
 const [visibleCompare, setVisibleCompare] = useState(false);  
 const [showTable, setShowTable] = useState(false); 
 const [textAreaValue,setTextAreaValue] = useState("");
 const [IngredientCompareList,setIngredientCompareList] = useCacheAlive([], `table-litermark-IngredientCompareList`)
 const [isModalVisibleUpload, setIsModalVisibleUpload] = useState(false);  
 const [selectedType, setSelectedType] = useState('3'); 
 const [IngredientExportList,setIngredientExportList] = useState([]); 
 const [viewStatus, setViewStatus] = useState(false); // 加载状态 


 const handleCompare = () => {  
  // 在这里，您可以处理比对逻辑，例如从服务器获取数据或进行本地比对  
  // 假设比对完成，现在显示表格 

  let form=[];
  textAreaValue.split("\n").map((item) => {
      if (item != "") {
      form.push(item)
      }
  });
  console.log(form,'form') 
  comparisonIngredient(form).then(response=>{
    if(response.data.status==0){
    let datalength=response.data.data.length
    message.success("比对成功,共有" + datalength +"条Ingredient不在数据库")
    let incilist=[]
    response.data.data.map(item=>{
        incilist.push({inci:item})
    })
    setIngredientExportList(response.data.data)
    setIngredientCompareList(incilist)
    setShowTable(true)
    // Ingredientstatus.value=1
    }
  
})
  // setShowTable(true);  
};

const Cpmparecolumns: any = [
  {
    title: 'INCI',
    dataIndex: 'inci',
    key: 'inci',
    width: 80,
  },
];

const handleTextAreaChange = (e) => {  
  setTextAreaValue(e.target.value);  
}; 


const handleExport = () => { // 添加了 async 关键字  
  
  // 导出表格到Excel  
  console.log(IngredientExportList,'IngredientExportList')
  downloadArr("/api/ingredient/downComparisonIngredient",
    IngredientExportList
  , `Inci List.xlsx`);
};  

const handleOpen = () => {  
  setTextAreaValue("");
  setVisibleCompare(true);  
};  

const handleClose = () => {  
  setVisibleCompare(false);  
  setShowTable(false); // 关闭弹窗时隐藏表格  
};  



  // 假设的获取数据函数  
  const fetchData = async (page1,pagesize2,search3) => {  
    // setLoading(true);  
    if(page1 == null || page1 == undefined || page1 == ""){
      page1=1
    } 
    if(pagesize2 == null || pagesize2 == undefined || pagesize2 == ""){
      pagesize2=10
    }
    if(search3 == null || search3 == undefined || search3 == ""){
      search3=null
    }
    // 模拟数据获取  
    let queryParam = {
      page: page1,
      limit: pagesize2,
      isdeleted:0,
      search:search3,
      orderby: "ingredient",
      order: 0,
      total: total,
      offset: 0
    }
    queryParam.offset = (queryParam.page - 1) * queryParam.limit;
    const { success, data}= await list(queryParam)
    setLitermarklist(data.data.body.page);  
    const se = [  
      {  
        title: t('Ingredient'),
        dataIndex: 'ingredient', // 假设 dataSource 中有一个名为 ingredient 的字段  
        key: 'ingredient',  
        width:150,
        // 可以添加其他属性，如 render、sorter 等  
        render: (text, record) => (  
          <a onClick={() => {  
            console.log(record,'record')
            setFormId(record.id)
            getIngredientSubjectTestById(record.id).then(response=>{
              const newUniqueSubjectLevels = new Set();  
                  let data1 =response.data.data
                  setTabData(data1)
                  const newSubjectLevels = [];  
                  data1.forEach(item => {  
                    item.subjectTestRespList.forEach(subItem => {  
                      const subjectLevel = `${subItem.zySafetySubjectDef.subjectLevel1Cn}/${subItem.zySafetySubjectDef.subjectLevel1En}`;  
                      newUniqueSubjectLevels.add(subjectLevel); // 使用Set来自动去重  
                    });  
                  });  
            const uniqueSubjectLevelsArray = Array.from(newUniqueSubjectLevels); 
            setTabSubjectLevel1(uniqueSubjectLevelsArray);
            getIngredientInfoById(record.id).then(res=>{
              let data = record
              data.reports =res.data.data.reports
              setReportList(data.reports)
              const reportData = res.data.data.reports
              data.reportScreens=res.data.data.reportScreens
              data.remarks=res.data.data.remarks
              data.reportCIR=[];
              data.reportLiterature=[];
              reportData.map(item=>{
                  if(item.origin == 'CIR' || item.origin ==''){
                    data.reportCIR.push(item)
                  }else{
                    data.reportLiterature.push(item)
                  }
              })
              setSelectedRow(data)
              setVisible(true);    
            }) 
          }) 
          }} style={{ color: 'blue', textDecoration: 'underline', cursor: 'pointer' }}>  
            {text}  
          </a>  
        ),  
      },  
      ...generateColumns(data.data.title), // 添加其他多级表头列  
    ]; 
    setTitleList(se) 
    setTotal(data.data.body.total) 
    console.log(se,'newCOlumn')
    // setLoading(false);  
  };  


  // 模态框内容（你可以根据需要填充）  
  const modalContent = () => {  
    if (!selectedRow) {  
      return null; // 如果没有选中行，则不渲染内容  
    }  
      if (selectedRow) {  
        // 这里可以添加你的模态框内容  
      const { ingredientName, ingredientEnglishName, originalText } = selectedRow; 

      return(
        <Row>  
        <Col span={6}>  
          <Card>  
            <div style={{ textAlign: 'center', fontWeight: 'bold' }}>Ingredient</div>  
            <List  
              bordered
              itemLayout="horizontal"  
              dataSource={[{ title: 'Ingredient中文：', description: selectedRow.ingredient }, { title: 'Ingredient英文：', description: selectedRow.inciUs }, { title: 'INCI序号：', description: selectedRow.lawInciSerial }, { title: '发现：', description: selectedRow.finding }, { title: '结论中文：', description: selectedRow.conclusionCn }, { title: '文献：', description: selectedRow.citation }, { title: '来源：', description: selectedRow.source }, { title: '附录备注', description: selectedRow.remark }, { title: 'SQ亚型：', description: selectedRow.description }, { title: '核验：', description: selectedRow.updateBy }]}  
              renderItem={item => (  
                <List.Item>  
                  <List.Item.Meta title={item.title} description={item.description} />  
                </List.Item>  
              )}  
            />  
            <div style={{ textAlign: 'center', marginTop: '16px', fontWeight: 'bold' }}>{t('searchDetail.OriginalFile')}</div>  
            <Row gutter={[16, 16]}>  
              {selectedRow.reports.map((item, index) => {  
                // 添加条件判断，确保 filename 存在才渲染 Col 组件  
                if (item.filename) {  
                  return (  
                    <Col key={index} span={24}>  
                      <Tooltip title={`决策： ${item.decisionRead}`} placement="top">  
                        <span  
                          onClick={() => window.open('/res-dir/Articel/Original/' + item.filename, '_blank')}  
                          className='spanHover'
                          style={{  
                            // 根据item.decisionRead的值设置样式  
                            color: item.decisionRead === 1 ? 'green' : 'red',  
                            textDecoration: 'underline',  
                          }}  
                        >  
                          {item.filename} ({item.dateReference})  
                        </span>  
                      </Tooltip>  
                    </Col>  
                  );  
                }  
                // 如果 filename 不存在，则不返回任何内容  
                return null;  
              })}  
            </Row> 
            {/* <div style={{ textAlign: 'center', marginTop: '16px', fontWeight: 'bold' }}>{t('ing.QuickCheckPage')}</div>  
            <Row gutter={[16, 16]}>  
            {selectedRow.reportScreens.map((item, index) => (  
                <Col key={index} span={24}>  
                    <span  
                      // href="#"  
                      onClick={() => window.open('/res-dir/Articel/Screen/' + item.filename, '_blank')}
                      style={{  
                        textDecoration: 'underline',  
                        color: 'green',  
                      }}  
                    >  
                      {item.filename}   
                    </span>   
                </Col>  
              ))}  
            </Row>    */}
            <div style={{ textAlign: 'center', marginTop: '16px', fontWeight: 'bold' }}>{t('fulu')}</div>  
            <Row gutter={[16, 16]}>  
            {selectedRow.remarks.map((item, index) => (  
                <Col key={index} span={24}>  
                    <span  
                      // href="#"  
                      style={{  
                        textDecoration: 'underline',  
                        color: 'green',  
                      }}  
                    >  
                      {item.remark}   
                    </span>   
                </Col>  
              ))}  
            </Row>   
          </Card>  
        </Col>  
        <Col span={18}>  
          <MyTabsComponent tabData={tabData} tabSubjectLevel1={tabSubjectLevel1} formId={formId} reportList={reportList}/>  
        </Col>  
      </Row>  
      )
    }    
    };  

  // 初始化数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 
    fetchData('','','');  
  }, []);  

    // 构建多级表头  
    const generateColumns = (columnsData) => {  
      return Object.keys(columnsData).map((key) => {  
        const subColumns = columnsData[key].map((subKey, index) => ({  
          title: subKey,  
          dataIndex: `${key}${subKey}`, // 假设数据源也是类似的多级结构  
          key: `${key}${subKey}`,  
          width:140,
        }));  
          
        return {  
          title: key,  
          key: key,  
          children: subColumns, 
          
        };  
      });  
    
    };  

  // 处理页码变化  
  const handlePageChange = (page,pageSize) => { 
    setCurrentPage(page)
    setPageSize(pageSize)
    fetchData(page,pageSize,''); // 获取新页的数据  
  };  

  // 重置函数  
  const handleReset = () => {  
      setIngredient(''); // 清空搜索框  
      // 可能还需要将 currentPage 重置为 1，取决于你的需求  
      // setCurrentPage(1);  
      fetchData(currentPage,pageSize,'')
    };  
  
  // 搜索函数  
  const handleSearch = () => {  
    fetchData(currentPage,pageSize,ingredient)
  };  

  // 假设的点击Ingredient的事件处理函数  
  const checkTheIngredient = (record) => {  
    console.log(record.ingredient);  
  };  

  const showModal = () => {  
    setIsModalVisibleUpload(true);  
  };  
  
  const handleFileChange = (info) => { 
    console.log(info,'info')
    info.file.status = "done"
    if(info.fileList.length==0){

    }else{
      setLoading(true);
      const files = info.fileList[0].originFileObj
        var formData = new FormData();
        formData.append("file", files);
            importIngredientInfoCheck(formData).then(response=>{
            console.log(response);
            if (response.data.status == 0) {
            // file.value=response.data;
                formData.append("test_id",selectedType);
                importIngredientInfoSave(formData).then(response=>{
                if (response.data.status == 0) {
                    message.success("Success")
                    info.fileList=[]
                    setLoading(false);
                    setIsModalVisibleUpload(false)
                }else{
                  const message1=response.data.data.join(',')
                  message.error("Error,Message:" + message1)
                  info.fileList=[]
                  setLoading(false)
                  setIsModalVisibleUpload(false)
                }
                })
            } else {
                const mes=response.data.data.join(',')
                message.error("Error,Message:" + mes + "列比对失败")
                info.fileList=[]
                setLoading(false)
                setIsModalVisibleUpload(false)
            }
            })
    }
    
  };  

  const handleFileChangeEndPoint = (info) => { 
    console.log(info,'info')
    info.file.status = "done"
    if(info.fileList.length==0){

    }else{
      setLoading(true);
      const files = info.fileList[0].originFileObj
        var formData = new FormData();
        formData.append("file", files);
        formData.append("test_id",selectedType);
        importSubject(formData).then(response=>{
        if (response.data.status == 0) {
            message.success("Success")
            info.fileList=[]
            setLoading(false);
            setIsModalVisibleUpload(false)
        }else{
          const message1=response.data.data.join(',')
          message.error("Error,Message:" + message1)
          info.fileList=[]
          setLoading(false)
          setIsModalVisibleUpload(false)
        }
        }).catch(()=>{
          message.error("Error")
          setLoading(false)
          setIsModalVisibleUpload(false)
        })
    }
    
  };  

  
  const handleCancel = () => {  
    setIsModalVisibleUpload(false);  
  };  
  
  const handleDownload = () => {  
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/exportConfig", {
    
    }, `Zan Ya Template_subject.xlsx`);
  };  
  
  const handleDownloadEndPoint = ()=>{
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/exportConfig2", {
    
    }, `Zan Ya Template_subject.xlsx`);
  }

  const handleTypeChange = (value) => {  
    setSelectedType(value);  
  };  
  return (  
    <div>  
      <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
      <Card className="box-card" style={{ marginBottom: 24, minWidth: '700px' }}>  
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>  
          <div style={{ flex: 1, marginRight: '20px' }}>  
            <div style={{ fontWeight: 'bold' }}>Ingredient</div>  
            <Input style={{ width: '240px' }} value={ingredient} onChange={(e) => setIngredient(e.target.value)} />  
          </div>  
          <div style={{ display: 'flex', alignItems: 'center' }}>  
            <Button onClick={handleReset} size='small' style={{ marginRight: '8px' }}>{t('cancel')}</Button>  
            <Button type="primary" size='small' onClick={handleSearch}>{t('search')}</Button>  
          </div>  
        </div>  
      </Card>
      <Card style={{marginTop:'2%'}}>
        <Button size='small' style={{marginBottom:'2%'}} type="primary" onClick={handleOpen}>  
          {t('IngredientCompare')}  
        </Button>  
        <Button size='small' disabled={viewStatus} type="primary" style={{marginLeft:'1%'}} onClick={showModal}>  
          {t('SubjectDataImport')}  
        </Button>  
        <Table  
          columns={titleList}  
          dataSource={litermarklist}  
          bordered  
          scroll={{ x: 'max-content' }} // 或者使用具体的像素值，如 '1000px'  
          pagination={false}
        />  
       <div style={{ display: 'flex', justifyContent: 'flex-start', marginTop: '16px' }}>  
        <Pagination  
          current={currentPage}  
          pageSize={pageSize}  
          total={total}  
          size='small'
          onChange={handlePageChange}  
        />  
      </div>  
      </Card>
       
      <Modal  
        title="Ingredient Details"  
        visible={visible}  
        onCancel={() => setVisible(false)}  
        footer={null}  
        width={1200}
        destroyOnClose
      >  
        {modalContent()}  
      </Modal> 

        <Modal  
        title="Compare Ingredient"  
        visible={visibleCompare}  
        onCancel={handleClose}  
        footer={null}  
        destroyOnClose
      >  
       {!showTable && (  
        <div>

         <Button type="primary"  style={{marginBottom:'2%'}} onClick={handleCompare}>  
         {t('compare')}  
          </Button>  
          <Input.TextArea autoSize={{ minRows: 5, maxRows: 10 }}  onChange={handleTextAreaChange}   value={textAreaValue}  placeholder='请输入INCI的英文名称，多个请换行，可黏贴'/>  
         </div>
       )}
       {showTable && (  
          <div>  
             <Button style={{marginBottom:'2%'}} type="primary" icon={<DownloadOutlined />} onClick={handleExport}>  
              {t('export')}  
            </Button>  
            <Table columns={Cpmparecolumns} dataSource={IngredientCompareList} />  
           
          </div>  
        )}  
      </Modal>  
      <Modal  
        title="Subject Data Import"  
        visible={isModalVisibleUpload}  
        onCancel={handleCancel}  
        footer={null} // 隐藏默认的footer
        destroyOnClose  
      >  
        <div style={{ marginBottom: '16px' }}>  
          <Button type="primary" onClick={handleDownload}>  
            {t('report.templateDownload')}  
          </Button>  
          <Button style={{marginLeft:'10px'}} type="primary" onClick={handleDownloadEndPoint}>  
            模板下载(文献与各条毒理学终点绑定) 
          </Button> 
        </div>  
        <p style={{ color: 'red', fontSize: '12px' }}>{t('IngredientUpload')}</p>  
        <div style={{ marginBottom: '16px' }}> 
        <span style={{color:'red',fontSize:'12px'}}>*</span><span style={{fontSize:'12px'}}>类型</span>
          <Select  
            defaultValue="3"  
            style={{ width: 120, marginLeft: '10px' }}  
            value={selectedType}  
            onChange={handleTypeChange}  
          >  
            <Option value="3">通用</Option>  
            <Option value="11">儿童</Option>  
          </Select>  
        </div>  
        <Divider style={{ marginBottom: '16px' }} />  
        <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                  // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                  // 例如，使用axios发送POST请求上传文件  
                  // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                onChange={handleFileChange} 
              >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
         </Upload> 

         <Upload  
                style={{marginTop:'10px'}}
                customRequest={({ file, onSuccess, onError }) => {  
                  // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                  // 例如，使用axios发送POST请求上传文件  
                  // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                onChange={handleFileChangeEndPoint} 
              >  
                <Button icon={<UploadOutlined />}>上传(文献与各条毒理学终点绑定)</Button>  
         </Upload> 
      </Modal>  
    </div>  
  );  
};  
  
export default literMark;